const Base = require('./base.js');
const salt = 'yichuanghqf';
const fs = require('fs');
const path = require('path');
module.exports = class extends Base {
  async loginAction() {
    const loginUser = await this.session('userInfo');
    if (loginUser) {
      return this.redirect('/index/index');
    }
    return this.display();
  }

  async loginInAction() {
    if (this.isPost) { // 如果是 POST 请求
      const {username, password} = this.post();
      // 1.查询数据库是否有此人，有则拿到用户的信息
      const user = await this.model('admin').where({username}).find();
      if (think.isEmpty(user)) {
        return this.fail('用户名不存在');
      }
      // 2.查询数据库的密码和当前用户密码是否匹配
      const saltPwd = think.md5(password + salt);
      if (saltPwd === user.password) {
        const resUser = formatUser(user);
        await this.session('userInfo', resUser);
        return this.success('登陆成功');
      } else {
        return this.fail('用户密码错误');
      }
    } else {
      return this.fail('不允许的请求');
    }
  }
  async uploadimgAction() {
    const file = this.file('file');
    const filepath = file.path;
    if (!file || !file.type) {
      return this.fail(-1, '图片不能为空', []);
    }
    if (file && (file.type === 'image/png' || file.type === 'image/jpg' || file.type === 'image/jpeg')) {
      var basename = path.basename(filepath);
      var pathEnd = think.datetime(new Date().getTime(), 'YYYYMMDD');
      var uploadDir = think.ROOT_PATH + '/www/upload/' + pathEnd;
      var uploadPath = uploadDir + '/' + basename;
      think.mkdir(uploadDir);

      const readStream = fs.createReadStream(filepath);
      const writeStream = fs.createWriteStream(uploadPath);
      readStream.pipe(writeStream);
      await readStream.on('end', function() {
        fs.unlinkSync(filepath);
      });

      var url = '/upload/' + pathEnd + '/' + basename;
      return this.success({url}, '上传成功!');
    } else {
      this.fail(-1, '请上传png或jpg格式的图片', []);
    }
  }
};

function formatUser(user) {
  const newUser = JSON.parse(JSON.stringify(user));
  delete newUser.password;
  delete newUser.deleted_at;
  return newUser;
}
